package com.jjwxc.jwjskandriod.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.BookDetailsActivity;
import com.jjwxc.jwjskandriod.activity.FindActivity;
import com.jjwxc.jwjskandriod.adapter.AllStackViewHolder;
import com.jjwxc.jwjskandriod.config.Constants;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.FFUtils;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.AllStackRequest;
import com.jjwxc.jwjskandriod.model.BookAlsoListResponse;
import com.jjwxc.jwjskandriod.model.ChannelListResponse;
import com.jjwxc.jwjskandriod.my.data.UserInfoBg;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.jjwxc.jwjskandriod.widget.OptionalPop;
import com.jjwxc.jwjskandriod.widget.PopViewUtil;
import com.jjwxc.jwjskandriod.widget.scroller.ConsecutiveScrollerLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class StackFragment extends Fragment {

    private View view;
    /**
     * 菜单标题
     */
    private final String[] TAB_T = new String[]{"全部", "言情", "纯爱", "衍生"};

    private String channels = "";
    private String word = "";
    private String sortType = "1";

    private String tab = "";

    private boolean isMonthSubs = false;
    private boolean isRefresh = true;
    RadioGroup tabLayout;
    LinearLayout ll_all;

    private RecyclerView rv_space;
    private AllStackAdapter adapter;
    TextView tv_all;
    ImageView img_jiantou;
    private LinearLayout ll_bg_vip;
    private ImageView img_find;


    TabLayout tabLayoutOne;
    TabLayout tabLayoutTwo;
    TabLayout tabLayoutThree;

    private int page = 0;
    private LinearLayout ll_option;
    private LinearLayout ll_sink;
    private ConsecutiveScrollerLayout csl_stack;
    private SwipeRefreshLayout refreshView;
    public static long lastRefreshTime;
    AllStackRequest allStackRequest = new AllStackRequest();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_stack, container, false);

            tabLayout = view.findViewById(R.id.tab_stack_layout);
            img_find = view.findViewById(R.id.img_find);
            ll_all = view.findViewById(R.id.ll_all);
            tv_all = view.findViewById(R.id.tv_all);
            img_jiantou = view.findViewById(R.id.img_jiantou);
            ll_bg_vip = view.findViewById(R.id.ll_bg_vip);
            tv_all.setText("全部");
            img_jiantou.setImageResource(R.mipmap.polygon_shang);
            ll_option = view.findViewById(R.id.ll_option);
            tabLayoutOne = view.findViewById(R.id.tab_allstack_one);
            tabLayoutTwo = view.findViewById(R.id.tab_allstack_two);
            tabLayoutThree = view.findViewById(R.id.tab_allstack_three);
            rv_space = view.findViewById(R.id.rv_allstack);
            csl_stack = view.findViewById(R.id.csl_stack);
            ll_sink = view.findViewById(R.id.ll_sink);
            refreshView = view.findViewById(R.id.stack_view);
            rv_space.setNestedScrollingEnabled(false);
            rv_space.setHasFixedSize(false);
            rv_space.setFocusable(false);
            rv_space.setLayoutManager(new LinearLayoutManager(getActivity()));
            rv_space.addItemDecoration(new LinearLayouDecoration(getActivity(),
                    LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
            setTabOne(null);
            String[] TAB_TITLES = new String[]{"默认", "30万以下", "30-50万", "50-100万", "100万以上"};
            setTabsTwo(tabLayoutTwo, getLayoutInflater(), TAB_TITLES, 2);
            String[] TAB = new String[]{"累计热度", "销售量", "完结时间"};
            setTabsTwo(tabLayoutThree, getLayoutInflater(), TAB, 3);
            setlinearLayoutTabs(tabLayout, getLayoutInflater(), TAB_T);

            setClickListener();
        }
        return view;
    }

    private List<ChannelListResponse.DataBean> mData = new ArrayList<>();

    public void setTabOne(String quan) {

        ((FFActivity) getActivity()).post(Url.listChannel, null, ChannelListResponse.class, new FFNetWorkCallBack<ChannelListResponse>() {
            @Override
            public void onSuccess(ChannelListResponse response) {
                if (response.getCode() == 200 && response.getData().size() > 0) {
                    mData.clear();
                    ChannelListResponse.DataBean bean = new ChannelListResponse.DataBean();
                    bean.setName("默认");
                    bean.setChannelId("");
                    mData.add(bean);
                    mData.addAll(response.getData());
                    setTabs(tabLayoutOne, getLayoutInflater(), mData);
                    page = 0;
                    afterCreate(page, quan);
                }
            }

            @Override
            public boolean onFail(ChannelListResponse response) {
                return false;
            }
        }, "{\"tab\":\"" + tab + "\"}");
    }

    public void setClickListener() {
        rv_space.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new AllStackAdapter(getActivity());
        rv_space.setAdapter(adapter);

        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        rv_space.setLayoutManager(manager);

        // 刷新
        refreshView.setOnRefreshListener(() -> {
            page = 0;
            afterCreate(page, null);
        });

        rv_space.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                int count = recyclerView.getAdapter().getItemCount();

                boolean isBottom = lastVisibleItemPosition == count - 1;

                // 如果 RecyclerView 滑动到底部，加载更多
                if (recyclerView.canScrollVertically(1) && isBottom) {
                    page += 1;
                    afterCreate(page * 10, null);
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        //当屏幕停止滚动，加载图片
                        if (getContext() != null) Glide.with(getContext()).resumeRequests();
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        //当屏幕滚动且用户使用的触碰或手指还在屏幕上，停止加载图片
                        if (getContext() != null) Glide.with(getContext()).pauseRequests();
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        //由于用户的操作，屏幕产生惯性滑动，停止加载图片
                        if (getContext() != null) Glide.with(getContext()).pauseRequests();
                        break;
                }
            }
        });

        //筛选项
        ll_option.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new OptionalPop().optionalPopWindow(v, getActivity(), allStackRequest, new OptionalPop.PopOptionalListener() {
                    @Override
                    public void onValueClick(AllStackRequest value) {
                        isRefresh = false;
                        allStackRequest = value;
                        if (value.getChannels() != null && value.getChannels().size() > 0) {
                            channels = value.getChannels().get(0);
                        }
                        if (!StUtils.isEmpty(value.getWordSize())) {
                            word = value.getWordSize();
                        }
                        if (!StUtils.isEmpty(value.getSortType())) {
                            sortType = value.getSortType();
                        }

                        int selectOne = 0;
                        int selectTwo = 0;
                        int selectThree = 0;
                        if (value.getChannels().size() > 0) {
                            for (int i = 0; i < mData.size(); i++) {
                                if (mData.get(i).getChannelId().equals(value.getChannels().get(0))) {
                                    selectOne = i;
                                }
                            }
                        }
                        tabLayoutOne.getTabAt(selectOne).select();
                        if (StUtils.isEmpty(value.getWordSize())) {
                            selectTwo = 0;
                        } else {
                            selectTwo = Integer.parseInt(value.getWordSize());
                        }
                        tabLayoutTwo.getTabAt(selectTwo).select();
                        if (StUtils.isEmpty(value.getSortType())) {
                            selectThree = 0;
                        } else {
                            selectThree = Integer.parseInt(value.getSortType()) - 1;
                        }

                        tabLayoutThree.getTabAt(selectThree).select();
                        if (!isRefresh) {
                            page = 0;
                            afterCreate(page, "");
                            isRefresh = true;
                        }

                    }
                });
                switch (tab) {
                    case "1":
                        MobclickAgent.onEvent(getContext(), UMConstant.STACKS_MORE_YANQING_CLICK);
                        break;
                    case "2":
                        MobclickAgent.onEvent(getContext(), UMConstant.STACKS_MORE_CHUNAI_CLICK);
                        break;
                    case "3":
                        MobclickAgent.onEvent(getContext(), UMConstant.STACKS_MORE_YANSHENG_CLICK);
                        break;
                    default:
                        MobclickAgent.onEvent(getContext(), UMConstant.STACKS_MORE_ALL_CLICK);
                        break;
                }
            }
        });
        img_find.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FindActivity.class);
                startActivity(intent);
            }
        });
        ll_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = "全部";
                if (tv_all.getText().toString().equals("全部")) {
                    text = "包月";
                    img_jiantou.setImageResource(R.mipmap.polygon_shang);
                } else {
                    text = "全部";
                }
                String finalText = text;
                PopViewUtil.stackAllPop(ll_all, getActivity(), text, new PopViewUtil.PopDismissListener() {
                    @Override
                    public void onOkClick(String group) {
                        tv_all.setText(finalText);
                        img_jiantou.setImageResource(R.mipmap.polygon_xia);
                        isMonthSubs = !finalText.equals("全部");
                        csl_stack.scrollToChild(ll_sink);
                        page = 0;
                        afterCreate(page, "");
                    }
                });
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        // 動態更新背景
        LiveEventBus.get(Constants.Background, Integer.class).observe(this, integer -> {
            if (integer < UserInfoBg.INSTANCE.getBACKGROUND_RID().length) {
                ll_bg_vip.setBackgroundResource(UserInfoBg.INSTANCE.getBACKGROUND_RID()[integer]);
            } else {
                ll_bg_vip.setBackgroundResource(R.color.white);
            }
        });
    }


    /**
     * 设置页卡显示效果
     *
     * @param tabLayout
     * @param inflater
     * @param tabTitlees
     */
    private void setlinearLayoutTabs(LinearLayout tabLayout, LayoutInflater inflater, String[] tabTitlees) {
        for (int i = 0; i < tabTitlees.length; i++) {
            RadioButton view = (RadioButton) inflater.inflate(R.layout.stack_item_fragment, null);
            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(FFUtils.getPx(75), FFUtils.getPx(26));
            layoutParams.setMargins(25, 0, 0, 0);
            view.setLayoutParams(layoutParams);
            if (i == 0) {
                view.setChecked(true);
                tab = "";
            }
            view.setId(i);
            view.setText(tabTitlees[i]);
            tabLayout.addView(view);
            int finalI = i;
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (finalI == 0) {
                        tab = "";
                    } else {
                        tab = finalI + "";
                    }
                    isRefresh = false;

                    tabLayoutTwo.getTabAt(0).select();
                    tabLayoutThree.getTabAt(0).select();
                    channels = "";
                    word = "";
                    sortType = "1";
                    allStackRequest = null;
                    allStackRequest = new AllStackRequest();
                    csl_stack.scrollToChild(ll_sink);
                    setTabOne("");

                    switch (tab) {
                        case "1":
                            MobclickAgent.onEvent(getContext(), UMConstant.PAGE_STACKS_YANQING);
                            break;
                        case "2":
                            MobclickAgent.onEvent(getContext(), UMConstant.PAGE_STACKS_CHUNAI);
                            break;
                        case "3":
                            MobclickAgent.onEvent(getContext(), UMConstant.PAGE_STACKS_YANSHENG);
                            break;
                        default:
                            MobclickAgent.onEvent(getContext(), UMConstant.PAGE_STACKS_ALL);
                            break;
                    }
                }
            });
        }
    }

    public void afterCreate(int page, String quan) {

        if (!StUtils.isEmpty(channels)) {
            List<String> channerl = new ArrayList<>();
            channerl.add(channels);
            allStackRequest.setChannels(channerl);
        } else {
            allStackRequest.setChannels(null);
        }
        allStackRequest.setTab(tab);
        allStackRequest.setWordSize(word);
        allStackRequest.setSortType(sortType);

        allStackRequest.setLimit(10);
        allStackRequest.setOffset(page);
        //开始网络请求
        getListBook(allStackRequest, quan);
    }

    public void getListBook(AllStackRequest allStackRequest, String quan) {
        allStackRequest.setIsMonthSubscribe(isMonthSubs);
        ((FFActivity) getActivity()).post(Url.listBook, quan, BookAlsoListResponse.class, new FFNetWorkCallBack<BookAlsoListResponse>() {
            @Override
            public void onSuccess(BookAlsoListResponse response) {
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() <= 0) {
                        refreshView.setRefreshing(false);
                    }
                    if (page == 0) {
                        refreshView.setRefreshing(false);
                        adapter.setData(response.getData());
                    } else {
                        adapter.addData(response.getData());
                    }
                }
            }

            @Override
            public boolean onFail(BookAlsoListResponse response) {
                return false;
            }
        }, JSON.toJSONString(allStackRequest));
    }

    /**
     * 设置页卡显示效果2
     */
    private void setTabsTwo(TabLayout tabLayout, LayoutInflater inflater, String[] list, int mPage) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allstack_item_tab, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_allstack_tab);
            tvTitle.setText(list[i]);
            tabLayout.addTab(tab);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isRefresh) {
                    if (mPage == 2) {
                        if (tab.getPosition() == 0) {
                            word = "";
                        } else {
                            word = tab.getPosition() + "";
                        }
                    } else {
                        sortType = (tab.getPosition() + 1) + "";
                    }
                    switch (StackFragment.this.tab) {
                        case "1":
                            if (mPage == 2) {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_WORD_COUNT_YANQING_CLICK);
                            } else {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_SORT_COUNT_YANQING_CLICK);
                            }
                            break;
                        case "2":
                            if (mPage == 2) {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_WORD_COUNT_CHUNAI_CLICK);
                            } else {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_SORT_COUNT_CHUNAI_CLICK);
                            }
                            break;
                        case "3":
                            if (mPage == 2) {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_WORD_COUNT_YANSHENG_CLICK);
                            } else {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_SORT_COUNT_YANSHENG_CLICK);
                            }
                            break;
                        default:
                            if (mPage == 2) {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_WORD_COUNT_ALL_CLICK);
                            } else {
                                MobclickAgent.onEvent(getContext(), UMConstant.STACKS_SORT_ALL_CLICK);
                            }
                            break;
                    }
                    page = 0;
                    afterCreate(page, "");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    public void setMonthState() {
        tv_all.setText("包月");
        img_jiantou.setImageResource(R.mipmap.polygon_xia);
        isMonthSubs = true;
        csl_stack.scrollToChild(ll_sink);
        afterCreate(0, "");
    }

    /**
     * 设置页卡显示效果
     *
     * @param tabLayout
     * @param inflater
     */
    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, List<ChannelListResponse.DataBean> list) {
        tabLayout.removeAllTabs();
        for (int i = 0; i < list.size(); i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.allstack_item_tab, null);
            // 使用自定义视图，目的是为了便于修改，也可使用自带的视图
            tab.setCustomView(view);
            TextView tvTitle = (TextView) view.findViewById(R.id.txt_allstack_tab);
            tvTitle.setText(list.get(i).getName());
            tabLayout.addTab(tab);
        }
        tabLayoutOne.postDelayed(new Runnable() {
            @Override
            public void run() {
                tabLayoutOne.getTabAt(0).select();
            }
        }, 100);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isRefresh) {
                    channels = list.get(tab.getPosition()).getChannelId();
                    afterCreate(0, "");
                    switch (StackFragment.this.tab) {
                        case "1":
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_TYPE_YANQING_CLICK);
                            break;
                        case "2":
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_TYPE_CHUNAI_CLICK);
                            break;
                        case "3":
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_TYPE_YANSHENG_CLICK);
                            break;
                        default:
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_TYPE_ALL_CLICK);
                            break;
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //最后再给刷新的权限
        isRefresh = true;
    }

    public class AllStackAdapter extends BaseRecyclerAdapter<AllStackViewHolder> {
        private Context context;


        private List<BookAlsoListResponse.DataBean> mData = new ArrayList<>();


        public AllStackAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<BookAlsoListResponse.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<BookAlsoListResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public AllStackViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.allstack_item_list, parent, false);
            AllStackViewHolder viewHolder_text = new AllStackViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public AllStackViewHolder getViewHolder(View view) {
            return new AllStackViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint({"SetTextI18n", "ClickableViewAccessibility"})
        @Override
        public void onBindViewHolder(final AllStackViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            FFImageLoader.loadImage(context, holder.img_allstack_item, mData.get(position).getCoverImgUrl() + "", mData.get(position).getBookId(), true);
            holder.tv_bookname_allstack.setText(mData.get(position).getName());
            holder.tv_book_author.setText(mData.get(position).getAuthor());
            holder.tv_book_info.setText(StUtils.reBlank(mData.get(position).getBookIntro()));
            holder.tv_allstack_tab.setText(mData.get(position).getChannlname());
            holder.cl_allstack_list.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);
                    switch (tab) {
                        case "1":
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_YANQING_CELL_CLICK);
                            break;
                        case "2":
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_CHUNAI_CELL_CLICK);
                            break;
                        case "3":
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_YANSHENG_CELL_CLICK);
                            break;
                        default:
                            MobclickAgent.onEvent(getContext(), UMConstant.STACKS_ALL_CELL_CLICK);
                            break;
                    }
                }
            });


        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }
}
